﻿using Microsoft.EntityFrameworkCore;
using SJ.Platform.Common;
using SJ.Platform.EFCore.Model;
using SJ.Platform.EFCore.Model.FlowManager;
using SJ.Platform.Extend.ModelExtend;
using SJ.Platform.Extend.ModelExtend.FlowExt;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Flow
{
    public class Flow_TypeHandle
    {
        private readonly SJDBContext _context;

        public Flow_TypeHandle(SJDBContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> CreateAsync(FlowType entity)
        {
            try
            {
                _context.FlowTypes.Add(entity);
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Flow_TypeHandle=>Create", ex);
                return false;
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateAsync(FlowType entity)
        {
            try
            {
                _context.Entry(entity).State = EntityState.Modified;
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Flow_TypeHandle=>Update", ex);
                return false;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Delete(FlowType entity)
        {
            try
            {
                _context.FlowTypes.Remove(entity);
                return _context.SaveChanges() > 0;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Flow_TypeHandle=>Delete", ex);
                return false;
            }
        }

        /// <summary>
        /// 根据主键删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteByIdAsync(string id)
        {
            try
            {
                var entity = _context.FlowTypes.Find(id);
                if (entity != null)
                {
                    _context.FlowTypes.Remove(entity);
                    await _context.SaveChangesAsync();
                    return true;
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Flow_TypeHandle=>DeleteById", ex);
            }
            return false;
        }


        /// <summary>
        /// 根据ID获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<FlowType> GetEntityByIdAsync(string id)
        {
            try
            {
                return await _context.FlowTypes.FindAsync(id);
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Flow_TypeHandle=>GetEntityById", ex);
            }
            return null;
        }


        /// <summary>
        /// 分页获取所有流程类型
        /// </summary>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public async Task<(List<FlowType> flows, int count)> GetAllAsync(int pageNumber, int pageSize, Expression<Func<FlowType, bool>> condition = null)
        {
            try
            {
                var query = _context.FlowTypes.AsQueryable();

                // 如果提供了查询条件，则应用它
                if (condition != null)
                {
                    query = query.Where(condition);
                }

                //总条数
                int count = await query.CountAsync();

                // 应用分页
                var skip = (pageNumber - 1) * pageSize;
                query = query.OrderByDescending(order => order.AddTime).Skip(skip).Take(pageSize);//倒序排列

                // 执行查询并返回结果
                var flows = await query.ToListAsync();

                return (flows, count);
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Flow_TypeHandle=>GetAllAsync  page", ex);
            }
            return (null, 0);
        }

        /// <summary>
        /// 获取所有项目流程类型
        /// </summary>
        /// <returns></returns>
        public async Task<List<FlowType>> GetProjectFlowTypeAsync()
        {
            try
            {
                var query = _context.FlowTypes.AsQueryable();
                query = query.Where(q => q.TypeName == "项目流程");

                // 执行查询并返回结果
                List<FlowType> flowtypes = new List<FlowType>();
                FlowType flowtype = await query.FirstAsync();
                flowtypes.Add(flowtype);
                await QueryChildAsync(flowtype, flowtypes);
                return flowtypes;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Flow_TypeHandle=>GetProjectFlowTypeAsync", ex);
            }
            return null;
        }
        /// <summary>
        /// 递归查询子项
        /// </summary>
        /// <param name="flowtype"></param>
        /// <param name="flowtypes"></param>
        private async Task QueryChildAsync(FlowType flowtype, List<FlowType> flowtypes)
        {
            try
            {
                var query = _context.FlowTypes.AsQueryable();
                query = query.Where(q => q.Pid == flowtype.Id);
                List<FlowType> fs = await query.ToListAsync();
                foreach (FlowType f in fs)
                {
                    flowtypes.Add(f);
                    await QueryChildAsync(f, flowtypes);
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Flow_TypeHandle=>QueryChild ", ex);
            }
        }

        /// <summary>
        /// 获取流程类型树
        /// </summary>
        /// <returns></returns>
        public async Task<List<FlowTypeExtend>> GetFlowTypeTreeAsync()
        {
            try
            {
                var query = _context.FlowTypes.AsQueryable();

                query = query.OrderByDescending(order => order.AddTime);//倒序排列

                // 执行查询并返回结果
                List<FlowType> flowtypes = await query.ToListAsync();
                List<FlowTypeExtend> flowTypeExtendList = new List<FlowTypeExtend>();

                BuildChild(flowTypeExtendList, flowtypes, flowtypes, 1);
                return flowTypeExtendList;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Flow_TypeHandle=>GetFlowTypeTreeAsync ", ex);
            }
            return null;
        }

        /// <summary>
        /// 递归生成子类型
        /// </summary>
        /// <param name="flowTypeExtendList"></param>
        /// <param name="flowTypeList"></param>
        /// <param name="sourceList"></param>
        /// <param name="level"></param>
        private void BuildChild(List<FlowTypeExtend> flowTypeExtendList, List<FlowType> flowTypeList, List<FlowType> sourceList, int level)
        {
            try
            {
                if (flowTypeList != null && flowTypeList.Count > 0)
                {
                    var pList = level == 1 ? flowTypeList.Where(m => string.IsNullOrWhiteSpace(m.Pid) || m.Pid == null).ToList() : flowTypeList;
                    foreach (var flowType in pList)
                    {
                        FlowTypeExtend flowTypeExtend = new FlowTypeExtend();
                        flowTypeExtend.Id = flowType.Id;
                        flowTypeExtend.TypeName = flowType.TypeName;
                        flowTypeExtend.Pid = flowType.Pid;
                        flowTypeExtend.PName = flowType.PName;
                        flowTypeExtend.AddUserId = flowType.AddUserId;
                        flowTypeExtend.AddTime = flowType.AddTime;
                        flowTypeExtend.EditTime = flowType.EditTime;
                        flowTypeExtend.EditUserId = flowType.EditUserId;

                        var childList = sourceList.Where(c => c.Pid == flowType.Id).ToList();
                        if (childList != null && childList.Count > 0)
                        {
                            if (flowTypeExtend.childFlowTypeList == null)
                            {
                                flowTypeExtend.childFlowTypeList = new List<FlowTypeExtend>();
                            }
                            BuildChild(flowTypeExtend.childFlowTypeList, childList, sourceList, 2);
                        }

                        flowTypeExtendList.Add(flowTypeExtend);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Flow_TypeHandle=>BuildChild", ex);
            }
        }
    }
}
